package com.weizhi.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

@Component
public class LoginGatewayFilter implements GatewayFilter, Ordered{

    private final static Logger logger = LoggerFactory.getLogger(LoginGatewayFilter.class);

    public static final String PASS_LOGIN = "PASS_LOGIN";

    public static final String FALSE = "0";

    @Autowired
    private RedisTemplate redisTemplate;

    //不需要登录 可访问的白名单
    public static final String [] whitePaths = new String[] {
        "/system/admin/user/login", "/system/admin/user/logout", "/system/admin/kaptcha"
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();
        logger.info("登录过滤path={}", path);
        if(!path.contains("admin")){// 不是控台请求不拦截
            return chain.filter(exchange);
        }

        //白名单不拦截
        if(isWhitePath(path)) return chain.filter(exchange);

        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("token");
        logger.info("登录拦截开始，token={}", token);
        if(StringUtils.isBlank(token)) {
            logger.warn( "token为空，请求被拦截" );
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Object userObj = redisTemplate.opsForValue().get(token);
        if(userObj == null){
            logger.warn( "token无效，请求被拦截" );
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        logger.info("已登录：{}", userObj);
        return chain.filter(exchange);
    }

    private boolean isWhitePath(String path) {
        for(String whitePath: whitePaths) {
            if(path.contains(whitePath)) return true;
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
